package com.moogle.aoejson;
 

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Content;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;

import com.moogle.domain.DocumentDomain;
/**
 * Servlet implementation class CrossSite
 */
public class CrossSite extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final ResourceBundle myResources = ResourceBundle
	.getBundle("db");
	private static String driverClassName;
	private static String url;
	private static String username;
	private static String password;
	private static String tablespace;
	static {
		driverClassName = myResources.getString("driverClassName");
		url = myResources.getString("url");
		username = myResources.getString("username");
		password = myResources.getString("password");
		tablespace = myResources.getString("tablespace");
	}
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CrossSite() {
        super();
        // TODO Auto-generated constructor stub
    }
	private Connection createConnection(){
		 Connection con = null;
	 	try {
			Class.forName(driverClassName);
			con = DriverManager.getConnection(url,username,password); 
			/*if (con != null) {
				 System.out.println(" connection obj = "+con.toString());
			}*/
	 	}catch (Exception e) {
				// TODO: handle exception
	 		e.printStackTrace();
		}
			return con;
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	//String json="{\"pbiId\": 1,\"pbiFileName\": \"banner1\",\"pbiFilePath\": \"banner1.jpg\",\"pbiThumbNailPath\": \"thumbbanner1.jpg\",\"pbiThumbNailName\": \"thumbbanner1\"}";
		String userid=request.getParameter("userid");
		System.out.println(" userid="+userid);
		List<DocumentDomain> documentDomains = getDocumentDomains(userid);
		  Factory factory = Abdera.getNewFactory();
	        Feed feed = factory.newFeed();
	        feed.setLanguage("en-US");
	        feed.setBaseUri("http://moogle.org");

	        feed.setTitle("Document Feed");
	        feed.addLink("http://moogle.org/");
	        feed.setUpdated(new Date());
	        feed.addAuthor("Chatchai Pimtun");
	        feed.setId("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6");
	        feed.addContributor("Chatchai Pimtun");
	        feed.addCategory("Document");
		for (DocumentDomain documentDomain : documentDomains) {
			Entry entry = feed.insertEntry();
	        entry.setTitle(documentDomain.getIfinicDocName());
	        entry.addLink(documentDomain.getIfinicDocLink());
	        entry.setId(documentDomain.getIfinicDocId()+"");
	        entry.setUpdated(new Date());
	       // entry.setSummary("Some text.");
		}
	/*	String json="test";
		System.out.println("into get");
*/
      

       /* // Creates an entry and inserts it at the beginning of the list
        Entry entry = feed.insertEntry();
        entry.setTitle("Atom-Powered Robots Run Amok");
        entry.addLink("http://example.org/2003/12/13/atom03");
        entry.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a");
        entry.setUpdated(new Date());
        entry.setSummary("Some text.");

        // Creates an entry and inserts it at the beginning of the list
        Entry entry2 = feed.insertEntry();
        entry2.setTitle("re: Atom-Powered Robots Run Amok");
        entry2.addLink("/2003/12/13/atom03/1");
        entry2.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-80cb323feb5b");
        entry2.setUpdated(new Date());
        entry2.setSummary("A response");

        // Creates an entry and appends it to the end of the list
        Entry entry3 = feed.addEntry();
        entry3.setTitleAsXhtml("<p>Test</p>");
        entry3.addLink("/2003/12/13/atom03/2");
        entry3.setId("HTTP://www.Example.org/foo/../bar", true); // normalizes the id to the value
                                                                 // http://www.example.org/bar
        entry3.setUpdated(new Date());
        entry3.setSummaryAsHtml("<p><a href=\"foo\">Test</a></p>").setBaseUri("http://example.org/site/");
        entry3.setSource(feed.getAsSource());

        // Out-of-line content
        Entry entry4 = feed.addEntry();
        entry4.setTitle("re: Atom-Powered Robots Run Amok");
        entry4.addLink("/2003/12/13/atom03/3");
        entry4.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-cafebabecafe");
        entry4.setUpdated(new Date());
        entry4.setSummary("An entry with out-of-line content");
        entry4.setContent(new IRI("http://example.org/0xcafebabe"), "text/html");

        // Base64 binary content
        Entry entry5 = feed.addEntry();
        entry5.setTitle("re: Atom-Powered Robots Run Amok");
        entry5.addLink("/2003/12/13/atom03/4");
        entry5.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-80cb323feb5c");
        entry5.setUpdated(new Date());
        entry5.setSummary("A simple Base64 encoded binary image"); 
        entry5.setContent(new IRI("http://example.org/0xcafebabe"), "text/html");

        // XML content
        Entry entry6 = feed.addEntry();
        entry6.setTitle("re: Atom-Powered Robots Run Amok");
        entry6.addLink("/2003/12/13/atom03/5");
        entry6.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-80cb323feb5d");
        entry6.setUpdated(new Date());
        entry6.setSummary("XML content");
        entry6.setContent("<a xmlns='urn:foo'><b/></a>", Content.Type.XML);*/

   
	   feed.getDocument().writeTo(response.getOutputStream());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	public List<DocumentDomain> getDocumentDomains(String userId) {
		 Connection connection = null;
			PreparedStatement pst1 = null;
			List<DocumentDomain> documentDomains = new ArrayList<DocumentDomain>();
		try { 
			connection = createConnection();
			//System.out.println(" user connection = "+connection.toString());
			String query = "SELECT *  from "+tablespace+".DOCUMENT WHERE IFINIC_DOC_USER_ID="+userId;
			if (connection != null) {
				try {
					pst1 = connection.prepareStatement(query.toString());
					ResultSet rs1 = pst1.executeQuery();
					  while (rs1.next()){
						  DocumentDomain documentDomain =new DocumentDomain();
						  documentDomain.setIfinicDocId(rs1.getInt("IFINIC_DOC_ID"));
						  documentDomain.setIfinicDocLink(rs1.getString("IFINIC_DOC_LINK")!=null?rs1.getString("IFINIC_DOC_LINK"):"");
						  documentDomain.setIfinicDocName(rs1.getString("IFINIC_DOC_NAME")!=null?rs1.getString("IFINIC_DOC_NAME"):"");
						  documentDomain.setIfinicDocStatus(rs1.getString("IFINIC_DOC_STATUS")!=null?rs1.getString("IFINIC_DOC_STATUS"):"");
						  documentDomain.setIfinicDocUserId(rs1.getInt("IFINIC_DOC_USER_ID"));  
						  documentDomains.add(documentDomain);
					   }
					
				} catch (SQLException e) {
					e.printStackTrace();
				} 
			} 
		} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	} finally {
		try {
			 if (pst1 != null) {
				pst1.close();
				pst1 = null;
			} 
			if (connection != null) {
				if (!connection.isClosed())
					connection.close();
				connection = null;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// e.printStackTrace();
		}
	}
		return documentDomains;
	}
}
